package com.yf.dxapp.module.app.component.app;

import com.qiniu.util.Auth;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @author yxmds
 */
@Slf4j
@Component
public class QiniuFileComponent {

    @Value("${Qiniu.img_domain}")
    private String imgDomain;

    @Value("${Qiniu.video_domain}")
    private String videoDomain;

    @Value("${Qiniu.AK}")
    private String AK;
    @Value("${Qiniu.SK}")
    private String SK;
    @Value("${Qiniu.bucket}")
    private String bucket;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String FILE_REDIS_PREFIX = "pfile_";

    private static final List<String> IMG_SUFFIX = Arrays.asList("bmp", "gif", "jpg", "jpeg", "pjpeg", "x-png", "png");

    private static final List<String> PDF_SUFFIX = Arrays.asList("pdf");

    private static final List<String> VIDEO_SUFFIX = Arrays.asList("mp4", "mov", "avi", "wmv", "flv", "mkv");

    private static final List<String> MUSIC_SUFFIX = Arrays.asList("mp3");

    private static final String HTTP_CODE = "http";

    private static final long EXPIRES = 604800;

    private static final String PRIVATE_FILE_TAG = "/private";


    public String complementImgUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        if (url.contains(HTTP_CODE)) {
            return url;
        }
        return imgDomain + url;
    }

    public String complementFileUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        if (url.contains(HTTP_CODE)) {
            return url;
        }
        String fileType = url.substring(url.lastIndexOf('.') + 1, url.length()).toLowerCase();
        if (IMG_SUFFIX.contains(fileType)) {
            return imgDomain + url;
        } else if (VIDEO_SUFFIX.contains(fileType)) {
            return privateFileUrl(videoDomain + url);
        }
        return url;
    }

    public String privateFileUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        String simpleFileName = getSimpleName(url);
        String redisKey = FILE_REDIS_PREFIX + simpleFileName;
        log.info("获取隐私文件，redisKey={}", redisKey);
        if (stringRedisTemplate.hasKey(redisKey)) {
            String tem = stringRedisTemplate.opsForValue().get(redisKey);
            log.info("缓存privateDownloadUrl:{}",tem);
            return decode(tem);
        }
        Auth auth = Auth.create(this.AK, this.SK);
        String privateDownloadUrl = auth.privateDownloadUrl(url, EXPIRES);
        log.info("privateDownloadUrl:{}",privateDownloadUrl);
        // 设置redis缓存有效时间必文件有效时间短5分钟，以确保能刷新获取新的
        stringRedisTemplate.opsForValue().set(redisKey, privateDownloadUrl, EXPIRES - 300, TimeUnit.SECONDS);
        return decode(privateDownloadUrl);
    }

    public String decode(String url){
        //如果URL是转码的 为了暂时兼容ios 给解码
        if(isURLEncoded(url)){
            url = URLDecoder.decode(url);
        }
        log.info("url:{}",url);
        return url;
    }

    public String getToken() {
        Auth auth = Auth.create(this.AK, this.SK);
        String upToken = auth.uploadToken(this.bucket);
        return upToken;
    }

    private String getSimpleName(String url) {
//        int indexBegin = url.indexOf(videoDomain.replace("https://", "")) + videoDomain.length();
//        if (indexBegin < 0) {
//            return url;
//        }
//        String suffix = VIDEO_SUFFIX.stream().filter(p -> url.contains(p)).findFirst().orElse(".mp4");
//        int indexEnd = url.indexOf(suffix);
//        if (indexEnd < 0) {
//            indexEnd = url.length() - 1;
//        }
//        return url.substring(indexBegin, indexEnd);
        return url.replace(videoDomain,"");
    }

    public static String getSimpleUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
//        UrlBuilder urlBuilder = UrlBuilder.ofHttp(url);
//        urlBuilder.addQuery("e",null);
//        urlBuilder.addQuery("token",null);
        if (!url.contains("?")) {
            return url;
        }
        url = url.substring(0, url.indexOf("?")).replace("http:","https:");
        //如果URL是转码的 为了暂时兼容ios 给解码
        return url;
    }


    public static boolean isURLEncoded(String url) {
        Pattern ENCODED_PATTERN = Pattern.compile("%[0-9A-Fa-f]{2}");
        if (url == null || url.isEmpty()) {
            return false;
        }

        // Check if the URL contains percent-encoded sequences
        return ENCODED_PATTERN.matcher(url).find();
    }

}

